<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="globalSerchFormStyle"
      :label-position="labelPosition"
    >
      <el-row>
        <el-col :span="6" v-if="authUser">
          <el-form-item label="油企名称" prop="enterpriseId">
            <el-select
              v-model="queryParams.enterpriseId"
              placeholder="请选择油企名称"
              clearable
              size="small"
              style="width: 190px"
              @change="handleSelectChange"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="$store.state.user.userLevel != 2">
          <el-form-item label="油站名称" prop="stationId">
            <el-select
              v-model="queryParams.stationId"
              placeholder="请选择油站名称"
              clearable
              size="small"
              style="width: 190px"
            >
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="卡号" prop="physicalCardNo">
            <el-input
              v-model="queryParams.physicalCardNo"
              placeholder="请输入卡号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" prop="userPhone">
            <el-input
              v-model="queryParams.userPhone"
              placeholder="请输入手机号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!authUser">
          <el-form-item label="卡名称" prop="physicalCardName">
            <el-input
              v-model="queryParams.physicalCardName"
              placeholder="请输入卡名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="$store.state.user.userLevel == 2">
          <el-form-item label="时间">
            <el-date-picker
              style="width: 190px"
              v-model="dateRangeCreatedDate"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="$store.state.user.userLevel == 2">
          <el-form-item label="时间">
            <el-date-picker
              style="width: 190px"
              v-model="dateRangeCreatedDate"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="collapse">
        <el-col :span="6">
          <el-form-item label="订单号" prop="balanceNo">
            <el-input
              v-model="queryParams.balanceNo"
              placeholder="请输入订单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单状态" prop="balanceType">
            <el-select
              v-model="queryParams.balanceType"
              placeholder="请选择订单状态"
              clearable
              size="small"
              style="width: 190px"
            >
              <el-option
                v-for="item in balanceTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="持卡人" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入持卡人"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="企业名称" prop="userCompany">
            <el-input
              v-model="queryParams.userCompany"
              placeholder="请输入企业名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="collapse">
        <el-col :span="6" v-if="authUser">
          <el-form-item label="卡名称" prop="physicalCardName">
            <el-input
              v-model="queryParams.physicalCardName"
              placeholder="请输入卡名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="$store.state.user.userLevel != 2">
          <el-form-item label="时间">
            <el-date-picker
              style="width: 190px"
              v-model="dateRangeCreatedDate"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="支付方式" prop="methodPayment">
            <el-select
              v-model="queryParams.payment"
              placeholder="请选择支付方式"
              clearable
              size="small"
              style="width: 190px"
            >
              <el-option
                v-for="item in methodPayment"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          type="primary"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          id="closeSearchBtn"
          @click="
            (closeSearch) => {
              collapse = !collapse;
            }
          "
        >
          {{ collapse ? "收起" : "展开更多" }}
          <i :class="collapse ? 'el-icon-arrow-up ' : 'el-icon-arrow-down'"></i>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" type="primary" @click="exportRecord"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <div class="summary-container">
      <div class="summary-item f1">
        <div class="summary-item-box f1">
          <span class="summary-title">实体卡充值总计</span>
          <span class="summary-sum"
            >{{ recordSum.totalRechargeAmt || 0 }}元</span
          >
        </div>
      </div>
      <div class="summary-item f1">
        <div class="summary-item-box f1">
          <span class="summary-title">实体卡消费总计</span>
          <span class="summary-sum"
            >{{ recordSum.totalConsumptionAmt || 0 }}元</span
          >
        </div>
      </div>
      <div class="summary-item f1">
        <div class="summary-item-box f1">
          <span class="summary-title">实体卡余额总计</span>
          <span class="summary-sum"
            >{{ recordSum.totalBalanceAmt || 0 }}元</span
          >
        </div>
      </div>
    </div>

    <el-table :data="recordList">
      <!-- <el-table-column type="selection" width="55" align="left" /> -->
      <el-table-column
        label="油企名称"
        align="left"
        prop="enterpriseName"
        width="120"
        v-if="authUser"
      />
      <el-table-column
        label="油站名称"
        align="left"
        prop="stationName"
        width="140"
        show-overflow-tooltip
      />
      <el-table-column
        label="卡号"
        align="left"
        prop="physicalCardNo"
        width="140"
        show-overflow-tooltip
      />
      <el-table-column
        label="卡类型"
        align="left"
        prop="physicalCardType"
        width="140"
        show-overflow-tooltip
        :formatter="formatterType"
      />

      <el-table-column
        label="持卡人"
        align="left"
        prop="userName"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="手机号"
        align="left"
        prop="userPhone"
        width="180"
      />
      <el-table-column
        label="订单号"
        align="left"
        prop="balanceNo"
        width="180"
        show-overflow-tooltip
      />
      <el-table-column
        label="订单类型"
        align="left"
        prop="balanceType"
        width="120"
        :formatter="formatterBalanceType"
      />
      <el-table-column
        label="订单状态"
        align="left"
        prop="status"
        width="120"
        :formatter="formatterStatus"
      />
      <el-table-column
        label="支付方式"
        align="left"
        prop="payment"
        width="120"
        :formatter="formatterSPayment"
      />

      <el-table-column
        label="订单金额(元)"
        align="left"
        prop="amount"
        width="140"
      />

      <el-table-column
        label="充值立减优惠(元)"
        align="left"
        prop="rechargeDiscount"
        width="140"
        v-if="authUser"
      >
        <template slot-scope="scope">
          {{ scope.row.rechargeDiscount || 0 }}</template
        ></el-table-column
      >

      <el-table-column
        label="消费立减优惠(元)"
        align="left"
        prop="consumptionDiscount"
        width="140"
        v-if="authUser"
      >
        <template slot-scope="scope">
          {{ scope.row.consumptionDiscount || 0 }}</template
        >
      </el-table-column>

      <el-table-column
        label="立减优惠合计(元)"
        align="left"
        width="140"
        :formatter="forinvoiceSum"
      />

      <el-table-column
        label="余额(元)"
        align="left"
        prop="balanceAmount"
        width="120"
      />
      <el-table-column
        label="卡号"
        align="left"
        prop="physicalCardNo"
        width="180"
      />

      <el-table-column
        label="开票状态"
        align="left"
        prop="invoiceStatus"
        width="120"
        :formatter="forinvoiceStatus"
      />

      <el-table-column
        label="支付时间"
        align="left"
        prop="createTime"
        width="180"
      />

      <el-table-column
        label="企业名称"
        align="left"
        prop="userCompany"
        width="140"
      />

      <el-table-column
        label="卡名称"
        align="left"
        prop="physicalCardName"
        width="120"
      />

      <el-table-column fixed="right" label="操作" width="120" align="left">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.payment === 'pos' || scope.row.payment === 'wx'"
            type="text"
            size="small"
            :disabled="scope.row.refundStatus != 1"
            @click="refund(scope.row)"
            >退款</el-button
          >
          <el-button type="text" size="small" @click="recordBilling(scope.row)"
            >开票记录</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="fr"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[5, 10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 开票记录 -->
    <InvoiceRecord
      :invoiceDialog.sync="invoiceDialog"
      :currentRowData="currentRowData"
    ></InvoiceRecord>
  </div>
</template>
<script>
import { timeComparison } from "@/utils/timeConversion";
import InvoiceRecord from "./invoice_record.vue";
import {
  physicalCardBalanceList,
  physicalCardBalanceSatistics,
  physicalCardBalanceExport,
  physicalCardBalanceRefund,
} from "@/api/ic/info";
import { listEnterpriseStation } from "@/api/dept";
import { enterpriseList } from "@/api/station/order";
export default {
  components: { InvoiceRecord },
  name: "cardrecordList",
  data() {
    return {
      labelPosition: "right",
      // 折叠开关
      collapse: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卡编号表格数据
      infoList: [],
      statistics: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      openPay: false,
      // 是否弹出充值密码
      openPasswd: false,
      balanceTypes: [
        {
          value: "0",
          label: "未成功",
        },
        {
          value: "1",
          label: "成功",
        },
      ],
      methodPayment: [
        {
          value: "xj",
          label: "现金支付",
        },
        {
          value: "pos",
          label: "移动支付",
        },
        {
          value: "bka",
          label: "后台增加",
        },
        {
          value: "czkxf",
          label: "实体卡储值",
        },
        {
          value: "ref",
          label: "充值退款",
        },
        {
          value: "dekxf",
          label: "定额卡储值",
        },
        {
          value: "wx",
          label: "微信支付",
        },
      ],
      // 查询参数
      queryParams: {
        payment: null,
        icCardno: null,
        icContactsphone: null,
        cardType: null,
        icCardname: null,
        createDate: null,
        icContacts: null,
        password: null,
        amt: null,
        issecret: null,
        stationId: null,
      },
      page: 1,
      pageSize: 10,
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 数据合计
      recordSum: {},
      // 表单数据
      recordList: [],
      enterpriseList: [],
      stationList: [],
      dateRangeCreatedDate: [],

      invoiceDialog: false, // 开票记录弹框
      currentRowData: {}, // 当前选中行数据
    };
  },
  created() {
    this.getEnterpriseList();
    // 如果当前是油企账号，则获取该企业下的油站
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
    this.getData();
  },
  methods: {
    // 开票记录
    recordBilling(row) {
      this.currentRowData = row;
      this.invoiceDialog = true;
    },
    // 退款
    refund(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: "退款",
        message: h("p", null, [h("span", null, "是否确认退款？")]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            physicalCardBalanceRefund({ id: row.id }).then((res) => {
              if (res && res.code === 200) {
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg);
              }
            });
            done();
          } else {
            done();
          }
        },
      })
        .then((action) => {})
        .catch((action) => {});
    },

    // 导出
    exportRecord() {
      const queryParams = this.queryParams;

      // const time = timeComparison(
      //   30,
      //   "export",
      //   queryParams.beginTime,
      //   queryParams.endTime
      // );
      // if (!time) return;

      this.$confirm("是否确认导出所有订单记录?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return physicalCardBalanceExport(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    handleQuery() {
      this.getData();
    },
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.dateRangeCreatedDate = [];
      this.getData();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getData();
    },
    getData() {
      if (this.loading) return;
      this.loading = true;
      let queryData = this.getQueryData(this.queryParams);
      this.addDateRange(queryData, this.dateRangeCreatedDate);
      queryData = Object.assign(
        {
          pageNum: this.page,
          pageSize: this.pageSize,
        },
        queryData
      );

      // const time = timeComparison(
      //   30,
      //   "earching",
      //   queryData.beginTime,
      //   queryData.endTime
      // );
      // if (!time) return (this.loading = false);

      physicalCardBalanceList(queryData).then((res) => {
        if (res && res.code === 200) {
          this.recordList = res.rows;
          this.recordList.forEach((item) => {
            for (let key in item) {
              if (
                !item[key] &&
                ![
                  "rechargeDiscount",
                  "consumptionDiscount",
                  "refundStatus",
                ].includes(key)
              ) {
                item[key] = "-";
              }
            }
          });
          this.total = res.total;
        } else {
          this.recordList = [];
          this.total = 0;
        }
      });
      physicalCardBalanceSatistics(queryData).then((res) => {
        this.recordSum = res.data;
      });
      this.loading = false;
    },
    getQueryData(data) {
      let queryData = data;
      Object.keys(queryData).forEach((key) => {
        if (queryData[key] === "" || queryData[key] === undefined) {
          queryData[key] = null;
        }
      });
      return queryData;
    },
    // 根据油企获取油站
    handleSelectChange(value) {
      this.stationList = [];
      this.queryParams.stationId = null;
      this.getStationList(value);
    },
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.stationList = res;
      });
    },

    formatterType(row) {
      let types = {
        dek: "定额卡",
        czk: "储值卡",
      };
      return types[row.physicalCardType] ? types[row.physicalCardType] : "-";
    },

    formatterBalanceType(row) {
      let types = {
        dcz: "充值",
        dxf: "消费",
        cz: "充值",
        xf: "消费",
      };
      return types[row.balanceType] ? types[row.balanceType] : "-";
    },

    formatterStatus(row) {
      if (row.status == 1) {
        if (row.payment == "ref") {
          return "已退款";
        } else {
          return "已支付";
        }
      } else {
        return "支付失败";
      }
    },

    formatterSPayment(row) {
      let types = {
        xj: "现金支付",
        pos: "移动支付",
        wx: "微信支付",
        czkxf: "实体卡支付",
        dekxf: "实体卡支付",
        bka: "后台增加",
        ref: "-",
      };
      return types[row.payment] ? types[row.payment] : "-";
    },

    // 开票状态
    forinvoiceStatus(row) {
      let types = {
        0: "未开票",
        1: "已开票",
        2: "部分开票",
        3: "不支持开票",
      };
      return types[row.invoiceStatus] ? types[row.invoiceStatus] : "-";
    },

    // 合计
    forinvoiceSum(row) {
      const rechargeDiscount = row.rechargeDiscount
        ? parseFloat(row.rechargeDiscount)
        : 0;
      const consumptionDiscount = row.consumptionDiscount
        ? parseFloat(row.consumptionDiscount)
        : 0;
      let sum = rechargeDiscount + consumptionDiscount;
      return sum;
    },
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style scoped lang="scss">
.f1 {
  flex: 1;
}
.summary-container {
  width: 100%;
  border: 1px solid #e7e3e3;
  padding: 10px 5px;
  border-radius: 10px;

  margin-bottom: 25px;
  display: flex;
  flex-direction: row;

  .summary-item {
    display: flex;
    flex-direction: column;

    border-right: 1px dashed rgba(0, 0, 0, 0.1);

    .summary-item-box {
      border-bottom: 1px dashed rgba(0, 0, 0, 0.1);
      padding: 5px;
      display: flex;
      justify-items: center;
      align-items: center;
      flex-direction: column;

      .summary-title {
        font-size: 18px;
      }

      .summary-sum {
        font-size: 24px;
        font-weight: 700;
      }
    }
  }

  .summary-item:last-child {
    border-right: none;
  }

  .summary-item-box:nth-last-child(-n + 1) {
    border-bottom: none;
  }
}
</style>
